from typing import Optional, Iterable
from enum import Enum

from tortoise import models, BaseDBAsyncClient
from tortoise import fields

from core import get_password_hash,settings

from . import baseModel

class User(models.Model,baseModel.TimeBaseMode):
    username = fields.CharField(max_length=100,null=False,description="用户名",unique=True)
    password = fields.CharField(max_length=128,null=False,description="密码")
    fullname = fields.CharField(max_length=20,null=False,description="用户全名")
    department = fields.CharEnumField(settings.Department,max_length=20,null=False,description="部门")
    email = fields.CharField(max_length=30,null=False,description="邮件")
    phone = fields.CharField(max_length=11,null=False,description="手机号")
    role = fields.IntEnumField(settings.UserRole,null=False,description="用户角色")
    
    # 项目
    # projects : fields.ReverseRelation["Project"]
    
    # group_member : fields.ManyToManyRelation["ProjectGroups"]
    
    # project_member : fields.ManyToManyRelation["ProjectMembers"]
    
    class Meta:
        table = "user" # 指定表名
    
    class PydanticMeta:
        exclude = ("group_member","project_member","projects","audit_records","project_log")
    
    # 重写父类方法 默认保存时将密码加密
    async def save(
        self,
        using_db: Optional[BaseDBAsyncClient] = None,
        update_fields: Optional[Iterable[str]] = None,
        force_create: bool = False,
        force_update: bool = False,
    ) -> None:
        if force_create or "password" in update_fields:
            self.password = get_password_hash(self.password)

        await super(User, self).save(using_db, update_fields, force_create, force_update)
    